import React, { PropTypes, Component } from 'react';
import Table from './Table'
import { getAuthShop, ROOTURL_TABLE } from './../publicAPI/publicAPI';
import styles from './SimpleTable.css';

class ShopCommission extends Component {
    constructor(props) {
        super(props);
        this.state = {
            shopCommission: [],
            areaArray: []
        }
        //当前日期
        this.year = new Date().getFullYear();
        this.shopId = [];
        this.locationCommission;
    }
    componentWillMount() {
        getAuthShop({
            where: {
                dd: [['eq', false]]
            }
        }, (data) => {
            for(let shop of data) {
                this.shopId.push(shop.id);
            }
            this.getShopCommission();
        })
    }

    getShopCommission() {
        fetch(`${ROOTURL_TABLE}cafune/grip/griprewsum.api?year=${this.year}`, {
            method: 'POST',
            headers: {
                "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
            }
        }).then((response) => {
            if (response.ok) {
                return response.json();
            } else {
                throw new Error('获取门店提成数据失败')
            }
        }).then((data) => {
            let shop = data.shopIds.sort(function(a, b) {
                return a > b;
            });
            shop.filter((id) => {
                return this.shopId.indexOf(id) != -1;
            })
            let areaArray = [];
            this.locationCommission = [];
            shop.forEach((item) => {
                this.locationCommission.push(data[item])
                if (areaArray.indexOf(data[item].shopLoc) === -1) {
                  areaArray.push(data[item].shopLoc)
                }
            })
            this.setState({
                shopCommission: [].concat(this.locationCommission),
                areaArray
            })
        }).catch((error) => {
            alert("获取服务器内容失败");
        })
    }

    changeArea(e) {
      let areaSelect = e.target.value;
      let showData = this.locationCommission.filter((item) => {
          return item.shopLoc == areaSelect;
      })
      this.setState({
        shopCommission: showData,
      });
    }

    handleClick() {
        let yearSelect = this.refs.yearSelect.value;
        if(!yearSelect || !(/^2\d{3}$/.test(yearSelect))) {
            alert("内容不能为空或格式错误");
            this.refs.yearSelect.focus();
            return;
        }
        this.year = yearSelect;
        this.getShopCommission();
    }

    handleKeyPress(e) {
      if(e.keyCode == 13) {
        this.handleClick();
      }
    }

    //render thead
    tHead() {
        let data = [
            { name: "门店" },
            { name: "城市" },
            { name: "一月" },
            { name: "二月" },
            { name: "三月" },
            { name: "四月" },
            { name: "五月" },
            { name: "六月" },
            { name: "七月" },
            { name: "八月" },
            { name: "九月" },
            { name: "十月" },
            { name: "十一月" },
            { name: "十二月" },
            { name: "总" }
        ]
        const _width = {
                "0": "12%",
                "1": "10",
                "2": "6%",
                "3": "6%",
                "4": "6%",
                "5": "6%",
                "6": "6%",
                "7": "6%",
                "8": "6%",
                "9": "6%",
                "10": "6%",
                "11": "6%",
                "12": "6%",
                "13": "6%",
                "14": "6%"
        }

        return data.map((item, index) => {
            return <th style = {{ width: _width[index], backgroundColor: 'rgba(0,153,255,1)', border: 'none'}}
                        role = "1"
                        key = {index}> {item.name} </th>
        })
    }

    tBody() {
         let _data = this.state.shopCommission;
         if (_data) {
             return _data.map((item, index) => {
                    return( <tr key = { index }>
                    　   <td> {item.shopName} </td>
                         <td> {item.shopLoc} </td>
                         <td> {item['1']} </td>
                         <td> {item['2']} </td>
                         <td> {item['3']} </td>
                         <td> {item['4']} </td>
                         <td> {item['5']} </td>
                         <td> {item['6']} </td>
                         <td> {item['7']} </td>
                         <td> {item['8']} </td>
                         <td> {item['9']} </td>
                         <td> {item['10']} </td>
                         <td> {item['11']} </td>
                         <td> {item['12']} </td>
                         <td> {item.yearGrip} </td>
                     </tr>)
            });
        } else {
            return null;
        }
    }

    render() {
      return (
        <div>
          <div>
            <select value={this.state.areaSelect} onChange={this.changeArea.bind(this)}>
              <option value="请选择地区">请选择地区</option>
              {
                !this.state.areaArray[0]||this.state.areaArray.map((area, index) => {
                  return (
                    <option value={area} key={index}>{area}</option>
                  );
                })
              }
            </select>
            <label><input ref="yearSelect" onKeyPress={this.handleKeyPress.bind(this)} className={styles.input} placeholder="如：2017" />年</label>
            <button onClick={this.handleClick.bind(this)} style={{borderRadius: '5px', backgroundColor: '#add8e6',marginLeft: '5px', padding: '3px 6px', color:'#fff'}}>确定</button>
          </div>

          <div>
              <Table tHead={this.tHead.call(this)} tBody={this.tBody.bind(this)()} style={{width: '90%'}}/>
          </div>
        </div>
      );
    }
}
export default ShopCommission;
